<?php
namespace Todo\Service;
use Todo\Util\ArrayUtil;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class MessageService extends BaseService
{
    private static $__INSTANCE = null;

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new MessageService();

        return self::$__INSTANCE;
    }

    /**
     * 发送点对点消息
     * @param $title
     * @param $content
     * @param $toUserId
     * @param string $url
     */
    public function sendToUser($title, $content,  $toUserId, $send_time=0, $url=''){

        $sender = current_user(true);

        //保存消息内容
        $contentData = array(
            'type'        => 2,
            'title'    => $title,
            'content'    => $content,
            'url'         =>$url,
            'send_time' => $send_time ? $send_time : date('Y-m-d H:i:s'),
            'sender' => $sender['id'],
            'receiver' => 0,
            'receiver_type' => '1',
            'is_process' => '1'
        );
        $id = D('Todo/Msg/Content')->add($contentData);
        if(!$id){
            $this->_error = '保存消息失败';
            return false;
        }

        $contentData['id'] = $id;
        return $this->_writeUnread($contentData, $toUserId);
    }


    /** 推送系统消息
     * @param string $title 标题
     * @param string $content 内容
     * @param string $url='' 打开的链接
     * @param int $type=1 接收者类型：1=个人，2=部门，3=班级，4=群组
     * @param string|array $toUserId =0 接收人ID 支持以数组或,分隔的多个用户ID
     * @return bool 是否成功
     */
    public function pushMessage($title, $content, $url='', $type=1, $toUserId = 0)
    {
        //保存消息内容
        $contentData = array(
            'type'        => 1,
            'title'    => $title,
            'content'    => $content,
            'url'         =>$url,
            'send_time' => date('Y-m-d H:i:s'),
            'sender' => 0,
            'receiver' => 0,
            'receiver_type' => $type,
            'is_process' => '2'
        );
        if($type == 1){//个人
            $contentData['is_process'] = '1';
            $id = D('Todo/Msg/Content')->insert($contentData);
            if(!$id){
                $this->_error = '保存消息失败';
                return false;
            }
            if(!is_array($toUserId)) $toUserId = explode(',', $toUserId);

            $contentData['id'] = $id;
            return $this->_writeUnread($contentData, $toUserId);
        }else{
            if(!is_array($toUserId)) $toUserId = explode(',', $toUserId);
            foreach ($toUserId as $userId){
                $contentData['receiver'] = $userId;
                if(!D('Todo/Msg/Content')->insert($contentData)) {
                    $this->_error = '保存消息失败';
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 查询我的全部消息
     * @param $userId 用户ID
     * @param $isRead 是否已读 =null 查询全部消息  =0 未读  =1 已读
     * @param $page = 0 当前页码
     * @param $limit =10 分页限制
     */
    public function getAllMessage($userId, $isRead=null,$page=0, $limit=10){

        //处理未生产的消息
        $this->processMessage($userId);

        $read = D('Todo/Msg/Read');
        $where = array('to_user'=>$userId);
        if(!is_null($isRead)) $where['is_read'] = intval($isRead);

        $list = $read->pageSelect($where,$page,$limit, 'id DESC');
        if(!$list) return $list;

        $ids = ArrayUtil::getColumn($list, 'message_id');
        $message = D('Todo/Sys/Message');
        $clist = $message->field('id,title,url,send_time')->where(array('id'=>array('in', $ids)))->select();
        foreach ($list as &$row){
            foreach ($clist as $c){
                if($c['id'] != $row['message_id']) continue;
                $row['title'] = $c['title'];
                $row['url'] = $c['url'];
                $row['type'] = 1;
                $row['send_time'] = $c['send_time'];
            }
        }
        return $list;
    }

    /**
     * 查询我的全部消息
     * @param $userId 用户ID
     * @param $isRead 是否已读
     * @param $page = 0 当前页码
     * @param $limit =10 分页限制
     */
    public function getMessageCount($userId, $isRead=null){

        //处理未生产的消息
        $this->processMessage();

        $read = D('Todo/Msg/Read');

        $where = array('user_id'=>$userId);
        if(!is_null($isRead)) $where['is_read'] = $isRead;
        return $read->where($where)->count();
    }

    /**
     * 打开一条消息，如果未读则标记为已读状态
     * @param int $id read表ID
     * @return bool|mixed
     */
    public function read($id){
        $read = D('Todo/Msg/Read');
        $info = $read->where(array('id'=>$id))->find();
        if(!$info) return false;

        //标记已读
        if(!$info['is_read']){
            $info['is_read'] = 1;
            $info['read_time'] = date('Y-m-d H:i:s');
            $read->save($info);
        }

        return  D('Todo/Sys/Message')->where(array('id'=>$info['message_id']))->find();
    }

    /**
     * 写入未读
     * @param array $contentInfo 消息内容
     * @param array $userList 用户列表
     * @return bool
     */
    protected function _writeUnread($contentInfo, $userList){
        if(!is_array($userList)) $userList = explode(',', $userList);

        foreach ($userList as $userId){
            $msgData = array(
                'user_id'   => $userId,
                'content_id'   => $contentInfo['id'],
                'title' => $contentInfo['title'],
                'url' => $contentInfo['url'],
                'type' => $contentInfo['type'],
                'sender' => 0,
                'is_read' => '2',
                'sender_name' => '系统',
                'send_time' => $contentInfo['send_time'],
                'tnt_id'  =>auto_tnt()
            );
            if(!D('Todo/Msg/Read')->add($msgData)) {
                $this->error = '发送消息失败';
                return false;
            }
        }
        return true;
    }

    /**
     * 处理未生成的消息
     * @param int $userId 用户ID
     * @return bool
     */
    public function processMessage(){
        $message = D('Todo/Msg/Content');

        $list = $message->where(array('is_process'=>'2', 'tnt_id'=>TNT_ID, 'send_time'=>array('lt', date('Y-m-d H:i:s') )))->select();
        foreach ($list as $content){ //1=个人，2=部门，3=班级，4=群组
            if($content['receiver_type'] == '2'){
                $userList = D('Todo/Base/Teacher')->where(array('depart_id'=>$content['receiver']))->select();
            }elseif($content['receiver_type'] == '3'){
                $userList = D('Todo/Base/Student')->where(array('class_id'=>$content['receiver']))->select();
            }elseif($content['receiver_type'] == '4'){

            }

            if($userList) $this->_writeUnread($content, array_column($userList,'user_id'));

            $content['is_process'] = '1';
            $message->save($content);
        }
    }
}